import spock.lang.Specification

/**
 * Created at 2017/10/24 15:37
 * @author gongweixin
 */
class EachExample extends Specification {

    def "test each return"() {
        //each 中的return相当于for循环的中continue
        def list = []
        ["b", "c", "d"].each { it ->
            list.add(it)
            if (it == "c") {
                return
            }
            list.add(it)
        }

        expect:
        ["b", "b", "c", "d", "d"] == list
    }

    def "test each 执行顺序"() {
        def list = []
        def a = ""
        ["a", "b", "c"].each { it ->
            list.add(it)
            a += it
        }

        expect:
        ["a", "b", "c"] == list
        "abc" == a
    }

    def "test each exception"() {
        def list = []
        try {
            ["a", "b", "c"].each { it ->
                list.add(it)
                throw new RuntimeException()
            }
        } catch (Exception ignored) {
            list.add("a")
        }

        expect:
        ["a", "a"] == list
    }

    def "test each remove"() {
        when:
        def map = ["a", "a", "b"].groupBy { it }
        map.keySet().remove("a")

        then:
        1 == map.keySet().size()
        ["b":["b"]] == map
    }
}
